package logs

import (
	"os"
	"time"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

type M map[string]interface{}

var logger *zap.Logger
var zapConfig struct {
	project  string
	logstore string
}

var aliyunLogger *zap.Logger
var aliyunConfig struct {
	project  string
	logstore string
}

var defaultLogger *zap.Logger

var serverName string

//
func initLogger(logPath string, maxSize, MaxBackups int, timeEncoder zapcore.TimeEncoder) *zap.Logger {
	hook := lumberjack.Logger{
		Filename:   logPath,    // 日志文件路径
		MaxSize:    maxSize,    // megabytes
		MaxBackups: MaxBackups, // 最多保留3个备份
		MaxAge:     10,         // days
		LocalTime:  false,
		Compress:   false, // 是否压缩 disabled by default
	}
	w := zapcore.AddSync(&hook)

	encoderConfig := zapcore.EncoderConfig{
		TimeKey:        "time",
		NameKey:        "logger",
		MessageKey:     "topic",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.LowercaseLevelEncoder,
		EncodeTime:     timeEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}

	core := zapcore.NewCore(
		zapcore.NewJSONEncoder(encoderConfig),
		w,
		zap.InfoLevel,
	)

	return zap.New(core)
}

func GetMillisecond(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
	nanos := t.UnixNano()
	millis := float64(nanos / int64(time.Millisecond))
	enc.AppendFloat64(millis)
}

func GetSecond(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
	enc.AppendFloat64(float64(t.Unix()))
}

type LogConf struct {
	Project    string
	Logstore   string
	LogPath    string
	MaxSize    int
	MaxBackups int
	MessageKey string
}

func Init(zapConf, aliyunConf LogConf) {
	serverName, _ = os.Hostname()

	// 大数据分析打点(王亚)
	{
		logger = initLogger(zapConf.LogPath, zapConf.MaxSize, zapConf.MaxBackups, GetMillisecond)
		zapConfig.project = zapConf.Project
		zapConfig.logstore = zapConf.Logstore
	}

	// 阿里云打点
	{
		aliyunLogger = initLogger(aliyunConf.LogPath, aliyunConf.MaxSize, aliyunConf.MaxBackups, GetSecond)
		aliyunConfig.project = aliyunConf.Project
		aliyunConfig.logstore = aliyunConf.Logstore
	}

	// 自定义打点
	{
		defaultLogger = initLogger("./log.json", 1024, 10, GetSecond)
	}

	return
}
